//
//  RSNetworkAudioPlayer.m
//  RealScene
//
//  Created by 范强伟 on 2023/10/12.
//

#import "RSNetworkAudioPlayer.h"

@interface RSNetworkAudioPlayer ()
@property (nonatomic, strong) AVPlayer * player;
@property (nonatomic, strong) AVPlayerItem * item;

@property (nonatomic, assign)float currentTime;
@end

@implementation RSNetworkAudioPlayer


// 单例初始化方法
+ (instancetype)sharedInstance {
  static RSNetworkAudioPlayer *sharedInstance = nil;
  if (!sharedInstance) {
      sharedInstance = [[self alloc] init];
  }
  return sharedInstance;
}

- (void)setUrl:(NSString *)url{
    self.currentTime = 0;
    _url = url;
    NSURL *urls;
    if ([url containsString:@"http"]) {
        urls = [NSURL URLWithString:url];
    }else{
        urls = [NSURL fileURLWithPath:url];
    }
    [self playAudioWithURL:urls];
}

// 播放音频方法
- (void)playAudioWithURL:(NSURL *)url {
    self.isSeeking = NO;
    // 创建AVPlayerItem对象
    self.item = [AVPlayerItem playerItemWithURL:url];
    [self.player replaceCurrentItemWithPlayerItem:self.item];
    [self.player play];
    self.isPlaying = YES;
    if(self.playChangeBlock){
        self.playChangeBlock(YES);
    }
}

// 暂停音频方法
- (void)pauseAudio {
    self.isSeeking = NO;
    self.isPlaying = NO;
    [self.player pause];
    if(self.playChangeBlock){
        self.playChangeBlock(NO);
    }
    NSLog(@"%@",self.player);
}


- (void)playAudio{
    self.isSeeking = NO;
    [self.player play];
    self.isPlaying = YES;
    if(self.playChangeBlock){
        self.playChangeBlock(YES);
    }
    NSLog(@"%@",self.player);
}


// 恢复音频方法
- (void)resumeAudio {
    self.isSeeking = NO;
//    [self playAudioWithURL:RSURL(self.url)];
//    [self seekToTime:self.currentTime];
    self.isPlaying = YES;
    [self.player play];
    self.isPlaying = YES;
    if(self.playChangeBlock){
        self.playChangeBlock(YES);
    }
//  [[AVPlayer.currentPlayer play] performSelector:@selector(play)];
}

// 停止音频方法
- (void)stopAudio {
    self.isSeeking = NO;
    self.isPlaying = NO;
    [self.player pause];
    if(self.playChangeBlock){
        self.playChangeBlock(NO);
    }
//  [[AVPlayer.currentPlayer stop] performSelector:@selector(stop)];
}

- (void)seekToTime:(float)time{
    self.isSeeking = YES;
    __weak typeof(self) weakSelf = self;
    [self.player.currentItem seekToTime:CMTimeMake(time, 1) completionHandler:^(BOOL finished) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.isSeeking = NO;
    }];
}

- (AVPlayer *)player{
    if (!_player) {
        _player = [[AVPlayer alloc] init];
        __weak typeof(self) weakSelf = self;
        [_player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
            __strong typeof(weakSelf) strongSelf = weakSelf;
            strongSelf.currentTime = CMTimeGetSeconds(strongSelf.item.currentTime);
            float current = CMTimeGetSeconds(time);
            float total = CMTimeGetSeconds(strongSelf.item.currentTime);
            NSLog(@"CMTimeGetSeconds %f  %f",current,total);
            if(strongSelf.isPlaying){
                if(strongSelf.timeChangeBlock && !strongSelf.isSeeking){
                    strongSelf.timeChangeBlock(CMTimeGetSeconds(strongSelf.item.currentTime), CMTimeGetSeconds(strongSelf.item.duration));
                }
            }
            // 播放完成
            if ((current == total) && current > 0) {
                [strongSelf pauseAudio];
            }
        }];
    }
    return _player;
}
 
- (void)setIsMute:(_Bool)isMute{
    _isMute = isMute;
    [self.player setMuted:isMute];
}

//设置声音模式，在播放器页面直接调用这个方法(根据自己的需求设置模式即可)
- (void)setVolume{

    NSError *setCategoryError = nil;
    BOOL success = [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient
error: &setCategoryError];

    if (!success) {
        NSLog(@"设置失败，其他处理！");
    }
}

@end
